package com.gitee.zhangchenyan.takin.service;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.SneakyThrows;

import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;

public abstract class BaseServiceImpl<M extends BaseMapper<T>, T extends BaseEntity, PageParam extends BasePageParam> extends ServiceImpl<M, T> implements BaseService<T, PageParam> {
    @Override
    public boolean remove(T queryEntity) {
        QueryWrapper<T> queryWrapper = new QueryWrapper<>();
        queryWrapper.setEntity(queryEntity);
        return remove(queryWrapper);
    }

    @Override
    public boolean update(T updateEntity, T queryEntity) {
        UpdateWrapper<T> updateWrapper = new UpdateWrapper<>();
        updateWrapper.setEntity(queryEntity);
        return update(updateEntity, updateWrapper);
    }

    @Override
    public T getOne(T queryEntity) {
        QueryWrapper<T> queryWrapper = new QueryWrapper<>();
        queryWrapper.setEntity(queryEntity);
        return getOne(queryWrapper);
    }

    @Override
    public List<T> getList(T queryEntity) {
        QueryWrapper<T> queryWrapper = new QueryWrapper<>();
        queryWrapper.setEntity(queryEntity);
        return list(queryWrapper);
    }

    @Override
    public long count(T queryEntity) {
        QueryWrapper<T> queryWrapper = new QueryWrapper<>();
        queryWrapper.setEntity(queryEntity);
        return count(queryWrapper);
    }

    @Override
    public List<Map<String, Object>> listMaps(T queryEntity) {
        QueryWrapper<T> queryWrapper = new QueryWrapper<>();
        queryWrapper.setEntity(queryEntity);
        return listMaps(queryWrapper);
    }

    @Override
    public PageResult<T> getPage(PageParam pageParam) {
        long pageNumber = pageParam.getPageNumber();
        if (pageParam.getPageNumberStartIndex() == 0) {
            pageNumber = pageParam.getPageNumber() + 1;
        }
        Page<T> page = new Page<>(pageNumber, pageParam.getPageSize());
        Page<T> resultPage = this.page(page, getPageWrapper(pageParam));
        PageResult<T> pageResult = new PageResult<>();
        pageResult.setPageNumber(pageParam.getPageNumber());
        pageResult.setPageSize(pageParam.getPageSize());
        pageResult.setTotalNum(resultPage.getTotal());
        pageResult.setPages(resultPage.getPages());
        pageResult.setData(resultPage.getRecords());
        return pageResult;
    }

    public abstract Wrapper<T> getPageWrapper(PageParam pageParam);

}
